package cn.llyong.rpc.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @description:
 * @author: lvyong
 * @date: 2020年06月19日 13:27
 */
public class LocalHostUtil {

    /**
     * 获取主机名称
     * 
     * @return
     * @throws UnknownHostException
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取系统首选IP
     * 
     * @return
     * @throws UnknownHostException
     */
    public static String getLocalIP() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取所有网卡IP，排除回文地址、虚拟地址
     * 
     * @return
     * @throws SocketException
     */
    public static String[] getLocalIPs() {
        try {
            List<String> list = new ArrayList<>();
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface intf = enumeration.nextElement();
                if (intf.isLoopback() || intf.isVirtual()) {
                    continue;
                }
                Enumeration<InetAddress> inets = intf.getInetAddresses();
                while (inets.hasMoreElements()) {
                    InetAddress addr = inets.nextElement();
                    if (addr.isLoopbackAddress() || !addr.isSiteLocalAddress() || addr.isAnyLocalAddress()) {
                        continue;
                    }
                    list.add(addr.getHostAddress());
                }
            }
            return list.toArray(new String[0]);
        } catch (Exception e) {
            return null;
        }
    }
}